// pages/newProblem/newProblem.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')

Page({

  data: {
    isLocationShow: false,
    locationArray: ['门诊', '急诊', '住院部'],
    locationIndex: -1,
    typeModalShow: false,
    backTypeIndex: 0,
    secondTypeIndex: 0,
    backTypeArray: [],
    imgArray: [],
    selGoodsList: [],
    brokenList: [],
    solidBrokenList:[],
    maxImgLength: 9, //上传图片张数
    show: true,
    equipType: '轮椅',
    partsRequired: false,
    equipCodeRequired: true,
    otherTypeIdArr: ['1014','1013','1009','1011','1026','209','16','17','18','19','20','30','35'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      scrollHeight: app.getScrollHeight(0),
      typeInfo: JSON.parse(options.typeInfo),
      brokenList: JSON.parse(options.partList),
      solidBrokenList: JSON.parse(options.partList),
      hospitalIdSolid:options.hospitalId ? options.hospitalId : '',
      hospitalNameSolid: options.hospitalName ? options.hospitalName : '',
      hospitalId:options.hospitalId ? options.hospitalId : '',
      hospitalName: options.hospitalName ? options.hospitalName : '',
    })
    wx.setNavigationBarTitle({
      title: this.data.typeInfo.label,
    })
    let index = this.data.otherTypeIdArr.findIndex(item=>item==this.data.typeInfo.child.id);
    this.setData({
      partsRequired: this.data.typeInfo.child.isEquPart,
      equipCodeRequired: this.data.typeInfo.child.isEquCode,
      equipType: this.data.typeInfo.id==1017?'担架车':this.data.typeInfo.id==2?'轮椅':''
    })
    this.getCurUserHasRoles();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    that.personalModal = that.selectComponent("#personalModal");
    that.toast = that.selectComponent("#toast");
    console.log(that.toast)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    //添加物品
    if (that.data.addGoodsFlag) {
      let list = that.data.selGoodsList
      that.setData({
        show: false,
      })
      util.print('selGoodsList',list);
      for (var i = 0; i < list.length; i++) {
        that.selGoodsAdd(list[i]);
      }
      that.data.selGoodsList = [];
      that.setData({
        show: true,
      })
    }
    if (that.data.hospitalIdSolid) {
      that.getMaintainers(that.data.hospitalIdSolid);
    }else if(that.data.changedLocationInfo){
      let hospitalId = that.data.changedLocationInfo.hospitalId;
      let hospitalName = that.data.changedLocationInfo.hospitalName;
      that.data.changedLocationInfo = null;
      that.getMaintainers(hospitalId,hospitalName);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 判断当前角色是否是安装师傅
   */
  getCurUserHasRoles: function () {
    let that = this;
    lbbService.getCurUserHasRoles({}, function (res) {
      let isInstaller = false;
      if (res.data) {
        if (res.data.roleIds) {
          isInstaller = /'3'/.test(res.data.roleIds);
        }
        that.setData({
          isInstaller: isInstaller,
          maintainers: {
            maintainName: res.data.masterName,
            maintainUid: res.data.masterUid,
          }
        });
      }
    });
  },
  /**
   * 图片组件
   */
  setImgArr: function (e) {
    let that = this;
    let imgArray = e.detail;
    that.setData({
      imgArray: imgArray
    });
  },
  selectGoods: function (e) {
    let that = this;
    util.print("selectGoods", e.currentTarget.dataset.item, e.detail.value);
    let item = e.currentTarget.dataset.item;
    let addNum = e.detail.value;
    let brokenList = that.data.brokenList;
    for (const goodsItem of brokenList) {
      if (goodsItem.id == item.id) {
        goodsItem.accNum = addNum;
        break;
      }
    }
    that.setData({
      brokenList: brokenList,
    })
  },
  /**
   * 输入备注
   */
  inputDesc: function(e){
    let desc = e.detail.value;
    util.print('inputDesc',e);
    if(desc.length==100){
      this.toast.showToast('反馈内容不超过100字');
    }
  },
  /**
   * 选择负责人
   */
  toChooseMaintainer: function () {
    let that = this;
    let hospitalId = that.data.hospitalId?that.data.hospitalId:'';
    wx.navigateTo({
      url: '../../../chooseMaintainer/chooseMaintainer?hosId=' + hospitalId + '&type=1',
    })
  },
  /**
   * 选择医院
   */
  toChooseHospital: function(){
    if(this.data.equipCode||this.data.boxCode){
      return;
    }
    wx.navigateTo({
      url: '../../../chooseHospital/chooseHospital',
    })
  },
  newProblem: function (e) {
    console.log(e,'查看e')
    let that = this;
    console.log(that.data.equipInfo,'查看equipInfo')
    let formData = e.detail.value;
    util.print('newProblem', e);
    that.setData({
      formData: formData
    })
    let firstId = that.data.typeInfo.id;
    let secondId = that.data.typeInfo.child.id;
    if ((firstId==6||firstId==1)&&that.data.equipCodeRequired && !formData.boxCode) {
      that.toast.showToast('请输入控制盒编号');
      return;
    } else if ((firstId==3)&&that.data.equipCodeRequired && !formData.boxCode) {
      that.toast.showToast('请输入归位桩编号');
      return;
    } else if ((firstId==2||firstId==1017)&&that.data.equipCodeRequired && !formData.equipCode) {
      that.toast.showToast('请输入设备编号');
      return;
    } else if ((!that.data.equipCodeRequired && !formData.hospitalId) || (firstId==1038 && !formData.hospitalId)) {
      that.toast.showToast('请选择医院');
      return;
    } else if (formData.boxCode&&!that.data.pileInfo) {
      let text = firstId==3?'归位桩编号有误':'控制盒编号有误';
      that.toast.showToast(text);
      return;
    } else if (formData.equipCode&&!that.data.equipInfo) {
      that.toast.showToast('设备编号有误');
      return;
    } else {
      for(let i=0;i<that.data.brokenList.length;i++){
        if(that.data.brokenList[i].accNum==0){
          that.toast.showToast(that.data.brokenList[i].accName+'数量必须大于零');
          return;
        }
      }
      if(that.data.partsRequired&&that.data.brokenList.length==0){
        that.toast.showToast('请选择零部件');
        return;
      }
    }
    console.log(that.data.imgArray)
    let imgArray = that.data.imgArray;
    if (imgArray.length > 0) {
      wx.showLoading({
        title: '正在上传图片',
        mask: true
      })
      util.upLoadImg(app.globalData.header, imgArray, 0, [], that.newProblemBack);
    } else {
      that.newProblemBack([]);
    }
  },
  newProblemBack: function (imgIdArray) {
    let that = this
    that.setData({
      imgIdArray
    })
    let partList = []
    that.data.brokenList.forEach(item => {
      let current = {}
      Object.keys(item).forEach(key => {
        if (key == 'id') {
          current.id = item[key]
          console.log(current.id)
        }
        if (key == 'accNum') {
          current.accNum = JSON.stringify(item[key])
        }
      })
      if (current.id) {
        partList.push(current)
      }
    })
    // that.data.brokenList.forEach(item => {
    //   partList.push({id:item.id,accNum:item.accNum});
    // })
    console.log("partlist>>", partList)
    let equipInfo = that.data.equipInfo;
    let pileInfo = that.data.pileInfo;
    let formData = that.data.formData;
    lbbService.newProblem({
      questionId: parseInt(that.data.typeInfo.id), //整型
      secondType: that.data.partsRequired?0:parseInt(that.data.typeInfo.child.id), //整型
      pileCode: formData.boxCode ? parseInt(formData.boxCode) : 0,
      equipCode: formData.equipCode ? parseInt(formData.equipCode) : 0,
      isOk: formData.isOk ? formData.isOk : 0, //0待处理/1已处理
      isMail: formData.isMail?0:1, //0 邮寄 1 不邮寄
      hospitalId: formData.hospitalId?parseInt(formData.hospitalId):0, //整型
      position: formData.position?formData.position:'',
      maintain: formData.maintain ? formData.maintain : '', //字符串类型
      desc: formData.desc, //字符串类型
      leaseAccQuestionList: JSON.stringify(partList), //零件列表，字符串类型
      imgId: that.data.imgIdArray,
      userPhone: formData.userPhone ? formData.userPhone : '',
      boxType: pileInfo&&pileInfo.boxStructVer ? pileInfo.boxStructVer : '',
      equType: that.data.equipType,
      rentPhone: '',
    }, function (res) {
      that.toast.showToast('添加成功', 'success');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        })
      }, 2000)
    })
  },
  inputBoxCode: function (e) {
    let that = this;
    let boxCode = e.detail.value.replace(/[^0-9]/ig, "");
    if (boxCode) {
      that.setData({
        boxCode
      })
      that.getPileInfo();
    }
  },
  inputEquipCode: function (e) {
    let that = this;
    let equipCode = e.detail.value.replace(/[^0-9]/ig, "");
    that.setData({
      equipCode
    })
    if (equipCode) {
      that.getEquipInfo();
    }else {
      that.setData({
        equipInfo: null
      })
    }
  },
  getPileInfo: function () {
    let that = this;
    let boxCode = that.data.boxCode;
    that.setData({
      pileInfo: null
    })
    lbbService.getPileDetailInfo({
      hid: parseInt(boxCode)
    }, function (res) {
      if(that.data.hospitalIdSolid&&res.hospitalId!=that.data.hospitalIdSolid){
        that.toast.showToast('Z'+boxCode+'不属于'+that.data.hospitalNameSolid);
        return;
      }
      that.setData({
        pileInfo: res
      })
      if (res.hospitalId) {
        that.getMaintainers(res.hospitalId,res.pileHospital);
      }
    })
  },
  getEquipInfo: function () {
    let that = this;
    that.setData({
      equipInfo: null
    })
    lbbService.getEquipDetailInfo({
      equId: that.data.equipCode
    }, res => {
      if(that.data.hospitalIdSolid&&res.data.hospitalId!=that.data.hospitalIdSolid){
        that.toast.showToast('L'+that.data.equipCode+'不属于'+that.data.hospitalNameSolid);
        return;
      }
      if(that.data.typeInfo.id==2&&res.data.equipType=='担架车'){
        that.toast.showToast('L'+that.data.equipCode+'是担架车编号，请输入轮椅编号','warning',5000);
        return;
      }
      if(that.data.typeInfo.id==1017&&res.data.equipType=='轮椅'){
        that.toast.showToast('L'+that.data.equipCode+'是轮椅编号，请输入担架车编号','warning',5000);
        return;
      }
      that.setData({
        equipInfo: res.data,
        equipType: res.data.equipType
      })
      if (res.data.hospitalId&&!that.data.boxCode) {
        that.getMaintainers(res.data.hospitalId,res.data.hospitalName);
      }
    })
  },
  /**
   * 扫码获取控制盒编号
   */
  scanBoxCode: function () {
    let that = this;
    wx.scanCode({
      success(res) {
        console.log('scanCode-->', res);
        let qrc = '';
        let qrCode = res.result;
        if (!qrCode) {
          that.toast.showToast('二维码为空');
          return;
        }
        let reg = /^([A-Za-z0-9]{2}:){5}([A-Za-z0-9]{2}){1}$/;
        if (qrCode.indexOf(util.CONST_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
          //控制盒大二维码
          var rst = qrCode.split('/');
          qrc = rst[rst.length - 1];
          that.data.scan_qrc = qrc;
        } else if (reg.test(qrCode)) {
          //控制盒小二维码
          that.data.deviceId = qrCode;
          that.data.mac = qrCode.replace(/:/g, '');
          lbbService.getHpIdByMacId({
            mac: that.data.mac
          }, res => {
            that.setData({
              boxCode: res.data.pileId + '',
            })
            that.getPileInfo();
          })
          return;
        } else {
          that.toast.showToast('二维码错误');
          return
        }
        lbbService.getMacId({
          markCode: that.data.scan_qrc,
          system: 'Android'
        }, function (res) {
          if (res.pileId) {
            that.setData({
              boxCode: res.pileId + '',
            })
            that.getPileInfo();
          } else {
            that.toast.showToast('获取mac失败');
          }
        })
      },
    })
  },
  /**
   * 设备类型变化 暂时无用
   */
  equipTypeChange: function(e){
    util.print('equipTypeChange',e);
    this.data.equipType = e.detail.value;
  },
  /**
   * 选择位置
   */
  showLocationModal: function() {
    let that = this
    that.setData({
      isLocationShow: true
    })
  },
  hideLocationModal: function() {
    this.setData({
      isLocationShow: false
    })
  },
  //选择位置
  chooseLocation: function(e) {
    this.setData({
      locationIndex: e.currentTarget.dataset.location,
      isLocationShow: false
    })
  },
  //新增位置
  addLocation: function(e) {
    let that = this
    let choosedlocation = e.detail.value.location
    lbbService.addPosByHos({
      hospitalId: parseInt(that.data.hospitalId),
      position: choosedlocation
    },function(res){
      that.getLocationList(that.data.hospitalId)
      that.hideLocationModal()
    })
  },
  /**
   * 获取医院桩点位
   */
  getLocationList: function (hospitalId) {
    let that = this;
    lbbService.getPosByHos({ hospitalId: parseInt(hospitalId) }, function (res) {
      that.setData({
        locationArray: res.data
      })
      that.setData({
        locationIndex: that.data.locationArray.length - 1
      })
    })
  },
  /**
   * 选择零部件
   */
  toPartList: function () {
    let that = this;
    let type = 'chair';
    if(that.data.equipType=='担架车'){
      type = 'car';
    }
    if (that.data.typeInfo.id == 3) {
      type = 'pile';
    } else if (that.data.typeInfo.id == 1) {
      type = 'box';
    }
    wx.navigateTo({
      url: '../../../partList/partList?type=' + type + '&partList=' + JSON.stringify(that.data.brokenList),
    })
  },
  selGoodsAdd: function (selectGoods) {
    let index = this.data.brokenList.findIndex(item=>item.id==selectGoods.id);
    if(index>-1){
      this.data.brokenList[index].accNum = selectGoods.accNum;
    } else {
      this.data.brokenList.push(selectGoods);
    }
    this.setData({
      brokenList: this.data.brokenList
    });
    this.data.addGoodsFlag = false;
  },
  deletePart: function (e) {
    util.print('deletePart',e)
    let that = this
    let index = e.currentTarget.dataset.index
    let brokenList = that.data.brokenList
    brokenList.splice(index, 1)
    that.setData({
      brokenList
    })
  },
  getMaintainers: function (hospitalId,hospitalName) {
    let that = this;
    that.setData({
      hospitalId:hospitalId,
      hospitalName:hospitalName,
    })
    that.getLocationList(hospitalId);
    lbbService.getMaintainers({
      hospitalId: parseInt(hospitalId)
    }, function (res) {
      if (res.data.install && res.data.install.length > 0) {
        that.setData({
          maintainers: res.data.install[0]
        })
      }
    })
  }
})
